package com.vlyman.config;

import com.vlyman.rtn.consts.BaseRtn;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：
 *  Swagger配置类
 * @author chenjs
 * @date 2018/10/13 16:09
 **/
@Slf4j
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        log.info("初始化swagger配置");
        List<ResponseMessage> msgList = setGlobalResponseMessage();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET, msgList)
                .globalResponseMessage(RequestMethod.POST, msgList)
                .globalResponseMessage(RequestMethod.PUT, msgList)
                .globalResponseMessage(RequestMethod.DELETE, msgList)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private List<ResponseMessage> setGlobalResponseMessage() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(BaseRtn.SUCCESS.getCode()).message(BaseRtn.SUCCESS.getMsg()).build());
        responseMessageList.add(new ResponseMessageBuilder().code(BaseRtn.ERROR.getCode()).message(BaseRtn.ERROR.getMsg()).build());
        return responseMessageList;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restfun风格")
                .version("1.0")
                .build();
    }
}
